package com.vmware.elastic.document;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.gson.Gson;
import com.vmware.elastic.entity.User;
import org.apache.http.HttpHost;
import org.elasticsearch.action.DocWriteResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.common.xcontent.XContentType;

/**
 * @apiNote 演示创建文档
 */
public class DocumentCreate {
    private static Gson gson = new Gson();

    public static void main(String[] args) throws Exception {
        RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
                new HttpHost("10.192.193.98", 9200))
        );
        IndexRequest request = new IndexRequest();
        request.index("vmware");
        request.id("1001");
        User user = new User();
        user.setName("张三");
        user.setAge(18);
        user.setSex("男");
        //es client操作索引需要将java对象转为json格式
        String json = gson.toJson(user);
        request.source(json, XContentType.JSON);
        IndexResponse response = client.index(request, RequestOptions.DEFAULT);
        DocWriteResponse.Result result = response.getResult();
        System.out.println(result);//CREATED
        client.close();
    }
}
